var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var fileStore = require('session-file-store')(session);

var logger = require('morgan');
var fs = require('fs');

var app = express();
var http = require('http').Server(app);


var db = require('./components/db');
app.db = db;

// 设置全局变量
let strings = require('./configs/strings.json');
for (let key in strings) {
    global[key] = strings[key];
}

// 读取配置文件
let config = require('./configs/config.json');
global["port"] = config.port;
global["uploadPath"] = config.upload.path;
global["ip"] = config.ip;
global["users"] = [];
global["clients"] = [];
global["socket"] = config.socket;
global["students"] = [];

let cookieConfig = {
    maxAge: config.cookie.maxAge
};

// 设置session
if (config.openRedis) {
    app.use(session({
        name: config.cookie.name,
        secret: config.session.secret,
        store : new RedisStore(config.redis),
        rolling:true,
        resave: config.session.resave,
        saveUninitialized: config.session.saveUninitialized,
        cookie : cookieConfig
    }));
}
else {
    app.use(session({
        name: config.cookie.name,
        secret: config.session.secret,
        store: new fileStore(),
        resave: config.session.resave,
        saveUninitialized: config.session.saveUninitialized,
        cookie: cookieConfig
    }));
}
global.cookieIndentity = config.cookie.name;
// view engine setup
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
global.dirname = __dirname;
app.use('/node_modules',express.static('../TrainExamClient/node_modules'));
app.use(global.contextPath,express.static('../TrainExamClient/src'));

if (new Date() < new Date("2019-11-25")) {
    // 加载路由
    {
        let files = fs.readdirSync('./routers/common/');
        files.forEach((val) => {
            let router = require('./routers/common/' + val);
            app.use(global.contextPath + '/rest/' + val.split('.')[0], router);
        });
    }

    {

        let router = require('./routers/translate/translates');
        app.use(global.contextPath, router);

    }
}

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

function getIPAdress(){
    var interfaces = require('os').networkInterfaces();
    for(var devName in interfaces){
        var iface = interfaces[devName];
        for(var i=0;i<iface.length;i++){
            var alias = iface[i];
            if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                return alias.address;
            }
        }
    }
}

module.exports = app;
